package com.android.clinic.app.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.android.clinic.app.photo.BitmapTools;
import com.android.clinic.app.photo.Crop;
import com.android.clinic.app.ui.widget.dialog.CustomPickDialog;
import com.jiongbull.jlog.JLog;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by cheng on 2018/2/5.
 */
public class PhotoUtils {

    private Context mContext;
    private Activity mActivity;
    public static final int NONE = 0;
    public static final int PHOTO_ZOOM = 211; // 缩放
    public static final int PHOTO_RAPH = 111;// 拍照
    public static final String IMAGE_UNSPECIFIED = "image/*";
    private static String photoPath = "";// 照片路径
    private Intent intent;
    private Map<String, Object> mapInfo = new LinkedHashMap<>();

    public PhotoUtils(Context context) {
        this.mContext = context;
        this.mActivity = (Activity) mContext;
    }

    public void takePhoto() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File fileDir = new File(FileUtils.SDPATH);
            if (!fileDir.exists()) {
                fileDir.mkdirs();// 创建文件夹
            }
            photoPath = FileUtils.SDPATH + System.currentTimeMillis() + ".jpg";
            Uri uri;
            if (Build.VERSION.SDK_INT < 24) {
                uri = Uri.fromFile(new File(photoPath));
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                uri = FileProvider.getUriForFile(mContext, AppApplicationManager.getPackageName(mContext) + ".fileprovider", new File(photoPath));
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            }

        }
        mActivity.startActivityForResult(openCameraIntent, PHOTO_RAPH);

    }


    /**
     * 从相册读取
     */
    private void takeAlbum() {
        intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                IMAGE_UNSPECIFIED);
        mActivity.startActivityForResult(intent, PHOTO_ZOOM);

    }

    /**
     * 裁剪
     *
     * @param source
     */
    private void startPhotoZoom(Uri source) {
        Uri destination = Uri.fromFile(new File(mContext.getCacheDir(),
                "cropped"));
        Crop.of(source, destination).asSquare().start(mActivity);
    }

    /**
     * 显示选择对话框
     */
    public void showPhotoDialog() {
        mapInfo.put("0", "拍照");
        mapInfo.put("1", "从相册中选取");
        new CustomPickDialog(mContext).builder(mapInfo).setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .setOnPickItemClickListener((v, position, id) -> {
                    final String type = mapInfo.get(position + "").toString();
                    PermissionUtils.applyCamera(mContext, new PermissionUtils.CallBack() {
                        @Override
                        public void onGuarantee() {
                            if (type.equals("拍照")) {
                                takePhoto();
                            } else {
                                takeAlbum();
                            }
                        }

                        @Override
                        public void onDeny() {

                        }
                    });
                }).show();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data,
                                 ResultListener listener) {
        switch (requestCode) {
            case PHOTO_RAPH:
                File picture = new File(photoPath);
                JLog.e("photoPath---->", photoPath);
                if (!TextUtils.isEmpty(photoPath) && picture.exists()) {
                    // 设置文件保存路径这里放在跟目录下
                    BitmapTools.rotaingImageView(photoPath);// 先旋转图片
                    BitmapTools.saveBitmap(
                            BitmapTools.compressBitmapByPath(photoPath), photoPath);
                    startPhotoZoom(Uri.fromFile(picture));
                }

                break;
            case PHOTO_ZOOM:
                // 读取相册缩放图片
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                if (uri != null) {
                    startPhotoZoom(uri);
                }
                break;
            case Crop.REQUEST_CROP:
                if (data != null) {
                    if (listener != null) {
                        if (Crop.getOutput(data) == null) {
                            Toasty.show(mContext, "未能识别的图片", 1000);
                            return;
                        }
                        listener.crop(Crop.getOutput(data).getPath());
                    }
                }
                break;
        }
    }

    public interface ResultListener {
        void crop(String photoPath);
    }

    public void cleanCache() {
        Utils.getAllFiles(new File(FileUtils.SDPATH));
    }

}
